﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Thor.Common
{
    public class MessageManager
    {
        #region Fields

        private IMessageRepository _repository = null;

        #endregion

        #region Constructors

        public MessageManager(IMessageRepository repository)
        {
            _repository = repository;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Inserts a message.
        /// </summary>
        /// <param name="message"></param>
        public void Insert(Message message)
        {
            _repository.Insert(message);
        }

        /// <summary>
        /// Retrieves a message.
        /// </summary>
        /// <returns></returns>
        public Message Fetch()
        {
            return _repository.Fetch();
        }

        /// <summary>
        /// Peeks a message.
        /// </summary>
        /// <returns></returns>
        public Message Peek()
        {
            return _repository.Peek();
        }

        /// <summary>
        /// Deletes a message.
        /// </summary>
        /// <param name="message"></param>
        public void Delete(Message message)
        {
            _repository.Delete(message);
        }

        /// <summary>
        /// Deletes all messages.
        /// </summary>
        public void Clear()
        {
            _repository.Clear();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets a concrete implementation of IMessageRepository.
        /// </summary>
        /// <param name="assemblyPath">Full path to the assembly.</param>
        /// <param name="typeName">Full type name of the type in the assembly that implements IMessageRepository.</param>
        /// <returns></returns>
        public static IMessageRepository GetRepository(string assemblyPath, string typeName, Dictionary<string, object> repositoryParameters)
        {
            //Load the assembly from the specified path.
            Assembly assembly = Assembly.LoadFile(assemblyPath);

            //Load the type
            Type type = assembly.GetType(typeName);

            //Get the constructor
            Type[] constructorTypes = new Type[1];
            constructorTypes[0] = typeof(Dictionary<string, object>);
            ConstructorInfo constructorInfo = type.GetConstructor(constructorTypes);

            //Invoke the constructor and return a new instance
            if (constructorInfo != null)
                return constructorInfo.Invoke(new object[] { repositoryParameters }) as IMessageRepository;

            return null;
        }

        #endregion
    }
}
